package tests;


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.sql.*; 

public class ReadXMLFile {
 static String s1,s2,s3,s4,s5;
static int i;
 
	public static void main(String argv[]) {
 
	  try {
 
		File fXmlFile = new File("./file.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
 
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("urlentry");
		System.out.println("-----------------------");
 
		for (int temp = 0; temp < nList.getLength(); temp++) {
 
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		      Element eElement = (Element) nNode;
 
		       s1=getTagValue("url", eElement);
		       s2=getTagValue("frompage", eElement);
	             s3=getTagValue("host", eElement);
		       //i=Integer.parseInt(getTagValue("salary", eElement));
                    
                 //storing parsing data to database 
                   store(); 
		   }
		}
	  } catch (Exception e) {
		e.printStackTrace();
	  }
  }
 
  private static String getTagValue(String sTag, Element eElement) {
	NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
 
        Node nValue = (Node) nlList.item(0);
 
	return nValue.getNodeValue();
  }

public static void store()
{


 Connection con = null;
 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "frontier";
 String driverName = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "";
 try{
  Class.forName(driverName).newInstance();
 con = DriverManager.getConnection(url+dbName, userName, password);
 try{
  Statement st = con.createStatement();
  String query="insert into urlfrontier values('"+s1+"','"+s2+"','"+s3+"')";
  System.out.println(query);
  st.execute(query);
  

}
  catch(SQLException s){
  System.out.println(s);
  }
  con.close();
  }
  catch (Exception e){
  e.printStackTrace();
  }

}
 
}